/*
 * httphandlecharset.cpp
 *
 *  Created on: Apr 27, 2009
 *      Author: kuncai
 */
#ifndef HTTPHANDLECHARSET_H_
#define HTTPHANDLECHARSET_H_
#include "log.h"
#include "httphandle.h"
#include "date.h"
#include "characterset.h"
#include "resource.h"
using namespace Http;
#define NOACCEPTED -1 
#define IDENTITY 0 
#define UTF8 1
#define GB2312 2  

class HttpHandleCharset: public HttpHandle{
	private:
		int IsAccept(const char* cCharset, map<string,float>* qList){
			map<string,float>::iterator iter;
			iter = qList->find(cCharset);
			float q=0;
			if(iter != qList->end()){
				q = iter->second;
				if(q > 0){
					//gzip coding
					return 0;
				}
			}
			return -1;
		}
	public:
		void ProcessRequest(HttpRequest* httpRequest, HttpResponse* httpResponse){
			Log::Debug("In Charset\n");
			string sAcceptCharset = "";
			int iCharset = IDENTITY;
		    sAcceptCharset = httpRequest->GetHeader(Http::AcceptCharset);
			if(sAcceptCharset != ""){
				map<string,float>* qList = new map<string,float>();
				Log::Debug("HttpSpilt_q begin...\n");
				httpRequest->HttpSpilt_q(sAcceptCharset, qList);
				Log::Debug("HttpSpilt_q end...\n");
				if(IsAccept(Http::Utf8, qList)==0){
					iCharset = UTF8; 
				}else if(IsAccept(Http::Gb2312, qList)==0){
					iCharset = GB2312;
				}else if(IsAccept(Http::Any, qList)!=0){
					iCharset = NOACCEPTED;
				}
				delete qList;
			}
			if(iCharset != NOACCEPTED){
				if(iCharset != UTF8){

					if(iCharset == GB2312){
						//get file content
						Buffer* ptBufferIndex = httpResponse->GetContent();
						if(ptBufferIndex->GetLimit() == 0){
							string filepath = httpRequest->GetParam("url"); 
							ResourceItem* ptResourceItem = Resource::GetResource(filepath.c_str());
							ptBufferIndex = ptResourceItem->GetBuffer();
						}
						//end get file content
						Buffer bContent;	
						Log::Debug("Transform begin>>>\n");
						Log::Debug("%s\n",ptBufferIndex->GetByteBuffer());
						int ret = CharacterSetTransform::Transform( ptBufferIndex, "UTF-8" , &bContent, "gb2312" );
						if(ret == 0){
							httpResponse->SetContent(&bContent);
						}
						Log::Debug("%s\n",bContent.GetByteBuffer());
						Log::Debug("Transform end>>>\n");

					}

				}
				if(successor != NULL){
					successor->ProcessRequest(httpRequest, httpResponse);
				}

			}else{
				httpResponse->SetStatus("406");
				httpResponse->SetReason("Not Acceptable");
				if(error != NULL){
					error->ProcessRequest(httpRequest, httpResponse);
				}
			}

		}
};
#endif /* HTTPHANDLECHARSET_H_ */
